package dept

import (
	"context"
	"go-zero-project/common/excption"
	"go-zero-project/services/user/rpc/constans"
	"go-zero-project/services/user/rpc/internal/mapper"
	"go-zero-project/services/user/rpc/internal/mapper/bo"
	"go-zero-project/services/user/rpc/internal/mapper/entity"

	"go-zero-project/services/user/rpc/internal/svc"
	"go-zero-project/services/user/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDeptUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UpdateLogic) DeptUpdate(in *pb.DeptUpdateReq) (*pb.EmptyObj, error) {
	// 1.query deptId has exists
	deptMapper := mapper.NewDeptMapper()
	selectCount, err := deptMapper.SelectCount(l.svcCtx.DBEngin, bo.SysDeptBO{DeptId: in.DeptId,
		HasDelFlag: true, DelFlag: 0, NonParentId: true})
	if err != nil {
		return nil, err
	}
	if selectCount < 0 {
		return nil, excption.NewErrCode(constans.DeptNoExistError)
	}
	// 2.name has repeat
	deptEntity, err := deptMapper.SelectOne(l.svcCtx.DBEngin, bo.SysDeptBO{Name: in.Name,
		HasDelFlag: true, DelFlag: 0, NonParentId: true})
	if err != nil && err.Error() != "record not found" {
		return nil, err
	}
	if deptEntity.DeptId > 0 && deptEntity.DeptId != in.DeptId {
		return nil, excption.NewErrCode(constans.DeptRepeatError)
	}
	// 3.builder entity
	sysDeptEntity := entity.SysDeptEntity{
		DeptId: in.DeptId, Name: in.Name, ParentId: in.ParentId, OrderNum: int(in.OrderNum),
	}
	updateErr := deptMapper.Update(l.svcCtx.DBEngin, sysDeptEntity)
	if updateErr != nil {
		return nil, updateErr
	}
	// 4.return obj
	return &pb.EmptyObj{}, nil
}
